package com.letv.android.client.controller;

import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;
import android.support.v4.app.FragmentActivity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ProgressBar;

import com.letv.android.client.LetvSDK;
import com.letv.android.young.client.R;
import com.letv.android.client.listener.PlayActivityCallback;
import com.letv.android.client.view.LetvPlayGestureLayout;
import com.letv.android.client.view.LetvPlayGestureLayout.LetvPlayGestureCallBack;
import com.letv.component.player.Interface.OnVideoViewStateChangeListener;
import com.letv.core.constant.LetvConstant.DialogMsgConstantId;
import com.letv.core.constant.PlayConstant;
import com.letv.core.listener.OnRelevantStateChangeListener;
import com.letv.core.utils.LogInfo;
import com.letv.core.utils.StatisticsUtils;
import com.letv.core.utils.TipUtils;
import com.letv.core.utils.UIsUtils;
import com.letv.datastatistics.util.PageIdConstant;
import com.ledim.utils.ToastUtil;

/**
 *点播和直播公用父类
 *控制分发View组件事件
 */
public abstract class BasePlayController implements OnRelevantStateChangeListener, 
									OnVideoViewStateChangeListener, LetvPlayGestureCallBack {
	//播放器之上的容器
	private ViewGroup mPlayUpper;
	//播放器之下的容器（半屏才显示）
	private ViewGroup mPlayLower;
	//播放器之上的手势层
	protected LetvPlayGestureLayout mPlayGestrue;
	//手势 亮度的布局
	private View mBbrightnessLayout;
	//手势 声音的布局
	private View mVolumeLayout;
	//手势 亮度的ProgressBar
	private ProgressBar mBrightnessSeekbar;
	//手势 声音的ProgressBar
	private ProgressBar mVolumeSeekbar;
	//手势 进度的布局
	private View mProgressLayout;
	//锁屏按钮
	private ImageView mBtnLock;
	//手势声音icon
	private ImageView mVolumeIcon;
	
	protected Context mContext;
	//回调BaseActivity方法
	protected PlayActivityCallback mPlayCallback;
	//播放模式
	private int mLaunchMode = PlayConstant.PLAY_DEFAULT;
	//是否只有全屏播放
	private boolean mOnlyFull;
	//是否锁屏
	protected boolean mLock;
	//音量
	private AudioManager mAudioManager;
	//最大亮度
	private int mMaxBrightness;
	//最大声音
	private int mMaxVolume;
	//手势操作开始的声音点
	private int mOldVolume;
	//手势操作开始的亮度点
	private int mOldBrightness;
    // 直播半屏控制条
//    protected LiveHalfControllerBar mHalfController;
    // 直播全屏控制条
//    protected LiveFullControllerBar mFullController;
//	//隐藏手势锁handler
//	private Handler mlockHandler = new Handler() {
//		public void handleMessage(android.os.Message msg) {
//            hideLock();
//		};
//	};
	
	public BasePlayController(Context context, PlayActivityCallback playCallback) {
		this.mContext = context;
		this.mPlayCallback = playCallback;
	}
	
	//Flow初始化
	public void create() {
		//子类数据
		initData();
		
		//公用组件
		initPulicViews();
		
		//子类组件
		initViews();
		
		//初始化音量
		initSoundState();
		
		//开始数据请求
		startFlow();
	}
	
    @Override
    public void onSingleTapUp() {
//        if (UIsUtils.isLandscape(getActivity())) {
//            if (mFullController != null) {
//                mFullController.clickShowAndHide();
//                if (getActivity() != null && mPlayCallback.isPlaying()) {
//                    startLongWatchCountDown();
//                }
//            }
//        } else {
//            if (mHalfController != null) {
//                mHalfController.clickShowAndHide();
//            }
//        }
    }
    
    /**
     * 点击lock之后延时隐藏控件栏
     */
    private void delayHide(){
//        if (UIsUtils.isLandscape(getActivity())) {
//            if (mFullController != null) {
//                mFullController.show();
//            }
//        } else {
//            if (mHalfController != null) {
//                mHalfController.show();
//            }
//        }
        if (getActivity() != null && mPlayCallback.isPlaying()) {
            startLongWatchCountDown();
        }
    }
    
	/**
	 * 初始化直播和点播公用组件
	 */
	private void initPulicViews(){
		mPlayUpper = (ViewGroup) getActivity().findViewById(R.id.play_upper);
		mPlayLower = (ViewGroup) getActivity().findViewById(R.id.play_lower);
		mPlayGestrue = (LetvPlayGestureLayout) getActivity().findViewById(R.id.play_gestrue);
		mBbrightnessLayout = getActivity().findViewById(R.id.brightness_layout);
		mVolumeLayout = getActivity().findViewById(R.id.volume_layout);
		mBrightnessSeekbar = (ProgressBar) getActivity().findViewById(R.id.gesture_brightness_progress);
		mVolumeSeekbar = (ProgressBar) getActivity().findViewById(R.id.gesture_volume_progress);
		mVolumeIcon = (ImageView) getActivity().findViewById(R.id.gesture_volume_icon);
		mProgressLayout = getActivity().findViewById(R.id.progress_layout);
		mBtnLock = (ImageView) getActivity().findViewById(R.id.gesture_lock);
		
		//隐藏手势音量和按钮浮层
		mBbrightnessLayout.setVisibility(View.GONE);
		mVolumeLayout.setVisibility(View.GONE);
		mProgressLayout.setVisibility(View.GONE);
		
		//初始化音量
		mAudioManager = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE);
		if (mAudioManager.getMode() == AudioManager.MODE_INVALID) {
			mAudioManager.setMode(AudioManager.MODE_NORMAL);
		}
		initVolume(getMaxSoundVolume(), getCurSoundVolume());
		
		//初始化亮度
		mOldBrightness = getScreenBrightness();
        float britness= LetvSDK.getInstance().getBritness();
        if(britness!= 0) {
        	mOldBrightness= (int)(britness* 255);
        }
		initBrightness(getMaxBrightness(), mOldBrightness);
		
		mPlayGestrue.initializeData((float) getCurSoundVolume() / getMaxSoundVolume(),
				(float) mOldBrightness / getMaxBrightness());
		mPlayGestrue.setLetvPlayGestureCallBack(this, true);
		float britnes= LetvSDK.getInstance().getBritness();
        if(britnes != 0) {
            setBrightness(britnes);
        }
		
		//初始化手势锁状态
		mBtnLock.setImageResource(mLock ? R.drawable.letv_lock : R.drawable.letv_unlock);
		mPlayCallback.setLock(mLock);
		mBtnLock.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
			    delayHide();
				changeLockStatus();

				//5.7
				if(UIsUtils.isLandscape(getActivity())){//全屏
					if(mLock){
						//5.7需求
						StatisticsUtils.staticticsInfoPost(getActivity(), "0", "c68", "1014", 1, null, PageIdConstant.fullPlayPage, null, null, null, null, null);
					}else{
						StatisticsUtils.staticticsInfoPost(getActivity(), "0", "c68", "1015", 2, null, PageIdConstant.fullPlayPage, null, null, null, null, null);
					}
				}else{//半屏
					if(mLock){
						StatisticsUtils.staticticsInfoPost(getActivity(), "0", "c68", "1014", 1, null, PageIdConstant.halpPlayPage, null, null, null, null, null);
					}else{
						StatisticsUtils.staticticsInfoPost(getActivity(), "0", "c68", "1015", 2, null, PageIdConstant.halpPlayPage, null, null, null, null, null);
					}
				}
			}
		});
	}
	
	/**
	 * 获取actiivty,用于getIntent等操作
	 * @return
	 */
	public FragmentActivity getActivity() {
		return (FragmentActivity)mContext;
	}
	
	/**
	 * 是否只有全屏播放
	 * @param isOnlyFull
	 */
	public void setOnlyFull(boolean isOnlyFull){
		this.mOnlyFull = isOnlyFull;
	}
	
	/**
	 * 是否只有全屏
	 * @return
	 */
	public boolean isOnlyFull() {
		return mOnlyFull;
	}
	
	/**
	 * 获取播放器层container
	 * @return
	 */
	public ViewGroup getPlayUper(){
		return mPlayUpper;
	}
	
	/**
	 * 获取播放器下半屏container
	 * @return
	 */
	public ViewGroup getPlayLower(){
		return mPlayLower;
	}
	
	/**
	 * 得到当前音量
	 * */
	public int getCurSoundVolume() {
		return mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
	}
	
	/**
	 * 得到最大音量
	 * */
	public int getMaxSoundVolume() {
		return mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
	}
	
	/**
	 * 得到最大亮度
	 * */
	public int getMaxBrightness() {
		return 255;
	}
	
	/**
	 * 获得当前亮度
	 * @return
	 */
	public int getBrightness() {
		WindowManager.LayoutParams wl = getActivity().getWindow().getAttributes();
		float br = wl.screenBrightness;
		LogInfo.log("clf", "getBrightness....br="+br);
		if (br < 0) {
			br = 0.1f;
		}
		return (int) (br * 255);
	}
	
	/**
	 * 获得当前屏幕亮度值  0--255
	 */
	private int getScreenBrightness(){
		int screenBrightness=255;
		try {
			screenBrightness = Settings.System.getInt(getActivity().getContentResolver(), Settings.System.SCREEN_BRIGHTNESS);
		} catch (SettingNotFoundException e) {
		}
		return screenBrightness;
	}
	
	/**
	 * 初始化手势声音布局
	 * */
	public void initVolume(int max, int cur) {
		if (mVolumeSeekbar != null) {
			mMaxVolume = max;
			int curPercent = (int)((float)cur / mMaxVolume * 100);
			mVolumeSeekbar.setProgress(curPercent);
			setVolumeIcon(curPercent);
		}
	}
	
	/**
	 * 初始化手势亮度布局
	 * */
	public void initBrightness(int max, int cur) {
		if (mBrightnessSeekbar != null) {
			mMaxBrightness = max;
			int curPercent = (int)((float)cur / mMaxBrightness * 100);
			mBrightnessSeekbar.setProgress(curPercent);
		}
	}
	
	private void setVolumeIcon(int curPercent){
		if(curPercent == 0){
			mVolumeIcon.setImageResource(R.drawable.letv_sound_zero);
		} else if(curPercent > 0 && curPercent <= 50){
			mVolumeIcon.setImageResource(R.drawable.letv_sound_one);
		} else if(curPercent > 50 && curPercent < 100){
			mVolumeIcon.setImageResource(R.drawable.letv_sound_two);
		} else if(curPercent == 100){
			mVolumeIcon.setImageResource(R.drawable.letv_sound_three);
		}
	}
	
	/**
	 * lock状态
	 * @return mLock 返回当前手势锁状态
	 * */
	public boolean changeLockStatus() {
		mLock = !mLock;
		mBtnLock.setImageResource(mLock ? R.drawable.letv_lock : R.drawable.letv_unlock);
		if (mLock) {
			String toastMsg = TipUtils.getTipMessage(mContext,DialogMsgConstantId.PLAY_OPERATION_LOCK, R.string.play_operation_lock);
			ToastUtil.toast(toastMsg);

		} else {
			String toastMsg = TipUtils.getTipMessage(mContext,DialogMsgConstantId.PLAY_OPERATION_UNLOCK, R.string.play_operation_unlock);
			ToastUtil.toast(toastMsg);
		}
		mPlayCallback.setLock(mLock);
		
		return mLock;
	}
	
	//初始化音量
	private void initSoundState() {
		int currentValue = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
		int maxValue = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
		curVolume(maxValue, currentValue);
	}
	
    /**
     * 返回手势锁状态
     */
    public boolean isLock() {
		return mLock;
	}
    
	public void wakeLock() {
		mLock= false;
        mBtnLock.setImageResource(R.drawable.letv_unlock);
	}
	
	//设置亮度
	public void setBrightness(float value) {
		if (value > 1) {
			value = 1;
		}
		if (value < 0.1f) {// 亮度不能为 0 要不会黑屏
			value = 0.1f;
		}
		LogInfo.log("clf", "setBrightness....value="+value);
		WindowManager.LayoutParams wl = getActivity().getWindow().getAttributes();
		wl.screenBrightness = value;
		getActivity().getWindow().setAttributes(wl);
        LetvSDK.getInstance().setBritness(value);
	}
	
	/**
	 * 调节音量
	 * */
	public int setSoundVolume(int value, boolean isShow) {
		int maxValue = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
		if (value >= 0 && value <= maxValue) {
			mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, value, 0);
			volumeRegulate(isShow, value);
		}

		return maxValue;
	}
	
	/**
	 * 调节声音
	 * */
	public void volumeRegulate(boolean isShow, int pos) {
		if (isShow) {
			if (mVolumeLayout.getVisibility() != View.VISIBLE) {
				mVolumeLayout.setVisibility(View.VISIBLE);
				if(UIsUtils.isLandscape(getActivity())){
					StatisticsUtils.staticticsInfoPost(getActivity(), "0", "c66", "1003", 3,  null, PageIdConstant.fullPlayPage, null, null, null, null, null);
				}else{
					StatisticsUtils.staticticsInfoPost(getActivity(), "0", "c66", "1003", 3, null, PageIdConstant.halpPlayPage, null, null, null, null, null);
				}
			}
		}

		if (mVolumeSeekbar != null) {
			int curPercent = (int)((float)pos / mMaxVolume * 100);
			mVolumeSeekbar.setProgress(curPercent);
			setVolumeIcon(curPercent);
		}
	}
	
	/**
	 * 调节亮度
	 * */
	public void brightnessRegulate(boolean isShow, int pos) {
		if (isShow) {
			if (mBbrightnessLayout.getVisibility() != View.VISIBLE) {
				mBbrightnessLayout.setVisibility(View.VISIBLE);
				//5.7需求
				if(UIsUtils.isLandscape(getActivity())){
					StatisticsUtils.staticticsInfoPost(getActivity(), "0", "c66", "1002", 2, null, PageIdConstant.fullPlayPage, null, null, null, null, null);
				}else{
					StatisticsUtils.staticticsInfoPost(getActivity(), "0", "c66", "1002", 2, null, PageIdConstant.halpPlayPage, null, null, null, null, null);
				}
			}
		}
		if (mBrightnessSeekbar != null) {
			int curPercent = (int)((float)pos / mMaxBrightness * 100);
			mBrightnessSeekbar.setProgress(curPercent);
		}
	}
	
	/**
	 * 设置当前launchMode
	 * @param launchMode
	 */
	public void setLaunchMode(int launchMode) {
		this.mLaunchMode = launchMode;
	}
	
	/**
	 * 获取当前launchMode
	 * @return
	 */
	public int getLaunchMode() {
		return mLaunchMode;
	}
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		return false;
	}
	
	@Override
	public void onDoubleFingersDown() {
	}

	@Override
	public void onDoubleFingersUp() {
	}

	@Override
	public void onDoubleTap() {
	}

	@Override
	public void onRightScroll(float incremental) {
		int max = getMaxSoundVolume();
		int newVlaue = mOldVolume + (int) (max * incremental);
		if (newVlaue < 0) {
			newVlaue = 0;
		}
		if (newVlaue > max) {
			newVlaue = max;
		}

		setSoundVolume(newVlaue, true);
		curVolume(max, newVlaue);
	}

	int currentB = 0;

	@Override
	public void onLeftScroll(float incremental) {

        int max = getMaxBrightness();
		if(currentB == 0){
			mOldBrightness = getScreenBrightness();
            float bright= LetvSDK.getInstance().getBritness();
            mOldBrightness= bright== 0? mOldBrightness: (int)(bright* max);
			currentB = mOldBrightness;
		}
		int newVlaue = mOldBrightness+ (int)Math.floor((int) (max * incremental));
		LogInfo.log("clf", "onLeftScroll mOldBrightness="+mOldBrightness+",max * incremental="+max * incremental);
		if (newVlaue < 0) {
			newVlaue = 0;
		}
		if (newVlaue > max) {
			newVlaue = max;
		}
		LogInfo.log("clf", "onLeftScroll newVlaue="+newVlaue);
		brightnessRegulate(true, newVlaue);
		setBrightness((float) newVlaue / max);
	}

	@Override
	public void onTouchEventUp() {
		mVolumeLayout.setVisibility(View.GONE);
		mBbrightnessLayout.setVisibility(View.GONE);
		mProgressLayout.setVisibility(View.GONE);
	}

	@Override
	public void onDown() {
		mOldVolume = getCurSoundVolume();
		mOldBrightness = getBrightness();
		LogInfo.log("clf", "...onDown...mOldBrightness="+mOldBrightness);
	}
	
	@Override
	public void onLandscapeScroll(float incremental) {
	}

	@Override
	public void onLandscapeScrollFinish(float incremental) {
	}
	
	@Override
	public void onTouch() {
	}
	
	@Override
	public void onDownloadStateChange() {
	}
	
	//从Intent获取参数和数据初始化
	public abstract void initData();
	
	//初始化
	public abstract void initViews();
	
	//开始数据请求
	public abstract void startFlow();
	
	//获取播放码流
	public abstract int getPlayLevel();
	
	//重置
	public abstract void format();
	
	//全半屏旋转
	public abstract void changeDirection(boolean isLandscape);
	
	//设置声音widget
	public abstract void curVolume(int max, int progrees);
	
	//设置声音widget
	public abstract void curVolume(int max, int progrees, boolean isUp);
	
	//长时间观看提醒
	public abstract void startLongWatchCountDown();
	
	//取消长时间观看提醒Dialog
	public abstract void cancelLongTimeWatch();
	
	//登陆成功
	public abstract void onActivityResultLoginSuccess();

	//支付成功
	public abstract void onActivityResultPaySuccess(boolean isPaySucceed);
	
	//分享回调
	public abstract void onShareActivityResult(int requestCode, int resultCode, Intent data);
	
	//锁屏pause
    public abstract void lockScreenPause();

    //解锁播放
    public abstract void unLockSceenResume();
    
    //释放数据
    public abstract void onDestroy();
    
    //统计播放
    public abstract void onResume();
    //统计播放
    public abstract void onStop();
    
    /**
     * 根据launchMode获取点播，直播controller
     * @param context
     * @param launchMode
     * @param isFull
     * @param playCallback
     * @return
     */
    public static BasePlayController getPlayController(Context context, int launchMode, boolean isFull,
            PlayActivityCallback playCallback) {
//        BasePlayController controller = new PlayLiveController(context, playCallback);
//
//        controller.setOnlyFull(isFull);
//        if (launchMode == PlayConstant.LAUNCH_MODE_LIVE_URL) {
//            controller.setLaunchMode(PlayConstant.PLAY_LIVE_URL);
//        } else if (launchMode == PlayConstant.LAUNCH_MODE_LIVE_LUNBO) { // 轮播台
//            controller.setLaunchMode(PlayConstant.LiveType.PLAY_LIVE_LUNBO);
//        } else if (launchMode == PlayConstant.LAUNCH_MODE_LIVE_WEISHI) { // 卫视台
//            controller.setLaunchMode(PlayConstant.LiveType.PLAY_LIVE_WEISHI);
//        } else if (launchMode == PlayConstant.LAUNCH_MODE_LIVE_SPORTS) { // 体育
//            controller.setLaunchMode(PlayConstant.LiveType.PLAY_LIVE_SPORTS);
//        } else if (launchMode == PlayConstant.LAUNCH_MODE_LIVE_ENTERTAINMENT) { // 娱乐
//            controller.setLaunchMode(PlayConstant.LiveType.PLAY_LIVE_ENTERTAIN);
//        } else if (launchMode == PlayConstant.LAUNCH_MODE_LIVE_MUSIC) { // 音乐
//            controller.setLaunchMode(PlayConstant.LiveType.PLAY_LIVE_MUSIC);
//        } else if (launchMode == PlayConstant.LAUNCH_MODE_LIVE_OTHER) { // 其他
//            controller.setLaunchMode(PlayConstant.LiveType.PLAY_LIVE_OTHER);
//        } else if (launchMode == PlayConstant.LAUNCH_MODE_LIVE_ID) {
//            controller.setLaunchMode(PlayConstant.LiveType.PLAY_LIVE_PUSH);
//        } else if (launchMode == PlayConstant.LAUNCH_MODE_LIVE_SELECT_ID) {
//            // 直播大厅进，默认是热门
//            int mode = ((Activity) context).getIntent().getIntExtra("from", PlayConstant.PLAY_LIVE_REMEN);
//            controller.setLaunchMode(mode);
//            controller.setOnlyFull(true);
//        }
//
//        controller.create();
//
//        return controller;
		return null;
    }
}
